<template>
    <div class="stock-list-container">
        <el-card>
            <!-- 页面标题和操作 -->
            <template #header>
                <div class="card-header">
                    <span class="page-title">库存列表</span>
                    <div class="header-actions">
                        <el-button type="primary" @click="handleRefresh" :loading="loading">
                            <el-icon>
                                <Refresh />
                            </el-icon>
                            刷新
                        </el-button>
                        <el-button type="success" @click="handleExport">
                            <el-icon>
                                <Download />
                            </el-icon>
                            导出数据
                        </el-button>
                    </div>
                </div>
            </template>

            <!-- 错误提示 -->
            <el-alert v-if="error" :title="error" type="error" show-icon closable @close="stockStore.setError('')"
                style="margin-bottom: 20px;" />

            <!-- 搜索筛选区域 -->
            <!-- <div class="search-filter">
                <el-row :gutter="8" justify="end" class="compact-search">
                    <el-col :span="3">
                        <el-input v-model="stockStore.searchParams.vaccineName" placeholder="搜索疫苗名称" clearable
                            @clear="handleSearch" @keyup.enter="handleSearch">
                            <template #prefix>
                                <el-icon>
                                    <Search />
                                </el-icon>
                            </template>
                        </el-input>
                    </el-col>
                    <el-col :span="3">
                       <el-input v-model="stockStore.searchParams.manufacturer" placeholder="搜索生产厂家" clearable
                            @clear="handleSearch" @keyup.enter="handleSearch">
                            <template #prefix>
                                <el-icon>
                                    <Search />
                                </el-icon>
                            </template>
                        </el-input>
                    </el-col>
            
                    <el-col :span="3">
                        <el-button type="primary" @click="handleSearch" :loading="loading">
                            <el-icon>
                                <Search />
                            </el-icon>
                            搜索
                        </el-button>
                        <el-button @click="handleReset">
                            <el-icon>
                                <RefreshRight />
                            </el-icon>
                            重置
                        </el-button>
                    </el-col>
                </el-row>
            </div> -->

            <!-- 库存统计卡片 -->
            <div class="statistics-cards">
                <el-row :gutter="20">
                    <el-col :span="6">
                        <el-card shadow="hover" class="stat-card">
                            <div class="stat-item">
                                <div class="stat-icon total">
                                    <el-icon>
                                        <Box />
                                    </el-icon>
                                </div>
                                <div class="stat-content">
                                    <div class="stat-value">{{ stockStatistics.total }}</div>
                                    <div class="stat-label">疫苗种类</div>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card shadow="hover" class="stat-card">
                            <div class="stat-item">
                                <div class="stat-icon sufficient">
                                    <el-icon>
                                        <CircleCheck />
                                    </el-icon>
                                </div>
                                <div class="stat-content">
                                    <div class="stat-value">{{ stockStatistics.sufficient }}</div>
                                    <div class="stat-label">库存正常</div>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card shadow="hover" class="stat-card">
                            <div class="stat-item">
                                <div class="stat-icon warning">
                                    <el-icon>
                                        <Warning />
                                    </el-icon>
                                </div>
                                <div class="stat-content">
                                    <div class="stat-value">{{ stockStatistics.lowStock }}</div>
                                    <div class="stat-label">库存不足</div>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                    <el-col :span="6">
                        <el-card shadow="hover" class="stat-card">
                            <div class="stat-item">
                                <div class="stat-icon danger">
                                    <el-icon>
                                        <Close />
                                    </el-icon>
                                </div>
                                <div class="stat-content">
                                    <div class="stat-value">{{ stockStatistics.outOfStock }}</div>
                                    <div class="stat-label">已缺货</div>
                                </div>
                            </div>
                        </el-card>
                    </el-col>
                </el-row>
            </div>

            <!-- 数据表格 -->
            <div class="table-container">
                <el-table :data="filteredStockList" v-loading="loading" stripe style="width: 100%"
                    :default-sort="{ prop: 'availableQuantity', order: 'descending' }">
                    <el-table-column type="index" label="序号" width="60" align="center" />

                    <el-table-column prop="vaccineName" label="疫苗名称" min-width="180" show-overflow-tooltip>
                        <template #default="{ row }">
                            <div class="vaccine-name">
                                <span class="name-text">{{ row.vaccineName }}</span>
                                <el-tag v-if="row.needWarning" size="small" type="warning">
                                    需预警
                                </el-tag>
                            </div>
                        </template>
                    </el-table-column>

                    <el-table-column prop="manufacturer" label="生产厂家" width="140" show-overflow-tooltip />

                    <el-table-column prop="batchNumber" label="生产批号" width="140" align="center" />

                    <el-table-column prop="specification" label="规格" width="100" align="center" />

                    <el-table-column prop="storageCondition" label="存储条件" width="120" align="center">
                        <template #default="{ row }">
                            <el-tag>
                                {{ row.storageCondition }}
                            </el-tag>
                        </template>
                    </el-table-column>

                    <!-- 库存数量相关列 -->
                    <el-table-column prop="totalQuantity" label="总数量" width="100" align="center" />

                    <el-table-column prop="availableQuantity" label="可用数量" width="100" align="center" sortable>
                        <template #default="{ row }">
                            <span :class="getStockClass(row)">
                                {{ row.availableQuantity }}
                            </span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="lockedQuantity" label="锁定数量" width="100" align="center" />

                    <el-table-column prop="minStock" label="最低库存" width="100" align="center" />

                    <el-table-column prop="maxStock" label="最高库存" width="100" align="center" />

                    <el-table-column prop="stockStatus" label="库存状态" width="100" align="center">
                        <template #default="{ row }">
                            <el-tag :type="getStatusType(row.stockStatus)">
                                {{ stockStatusMap[row.stockStatus] || row.stockStatus }}
                            </el-tag>
                        </template>
                    </el-table-column>

                    <el-table-column prop="usageRate" label="使用率" width="100" align="center">
                        <template #default="{ row }">
                            <el-progress :percentage="Math.round(row.usageRate)"
                                :status="getUsageRateStatus(row.usageRate)" :show-text="false" />
                            <span>{{ row.usageRate }}%</span>
                        </template>
                    </el-table-column>

                    <el-table-column prop="updateTime" label="最后更新" width="160" align="center" />

                    <el-table-column label="操作" width="200" fixed="right" align="center">
                        <template #default="{ row }">
                            <el-button type="primary" link size="small" @click="handleViewDetail(row.vaccineId)">
                                <el-icon>
                                    <View />
                                </el-icon>
                                详情
                            </el-button>
                            <el-button type="success" link size="small" @click="handleAdjustStock(row.id)">
                                <!-- v-if="hasPermission(['SUPER_ADMIN', 'VACCINE_ADMIN'])" -->
                                <el-icon>
                                    <Edit />
                                </el-icon>
                                调整
                            </el-button>
                            <el-button type="warning" link size="small" @click="handleStockWarning(row)"
                                v-if="row.needWarning">
                                <el-icon>
                                    <Warning />
                                </el-icon>
                                预警
                            </el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>

            <!-- 分页 -->
            <div class="pagination-container">
                <el-pagination v-model:current-page="pagination.currentPage" :total="pagination.total"
                    :page-size="pagination.pageSize" layout="prev, pager, next" @current-change="handleCurrentChange" />
            </div>
        </el-card>
    </div>
</template>

<script setup>
import { useStockStore } from '/src/store/stock'
// import { useAuthStore } from '@/stores/auth'
import { storeToRefs } from 'pinia'
import { onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useRouter } from "vue-router";
const router = useRouter();
// 使用Store
const stockStore = useStockStore()
// const authStore = useAuthStore()

// 从Store中获取响应式状态
const { loading, error, searchParams, pagination, stockStatusMap } = storeToRefs(stockStore)
const { stockStatistics, filteredStockList } = storeToRefs(stockStore)

// // 权限检查
// const hasPermission = (roles) => {
//   const userRole = authStore.userInfo?.role || 'USER'
//   return roles.includes(userRole)
// }

// 获取库存状态标签类型
const getStatusType = (status) => {
    const statusMap = {
        'NORMAL': 'success',
        'LOW': 'warning',
        'OUT': 'danger',
        'OVER': 'info'
    }
    return statusMap[status] || 'info'
}

// 获取使用率状态
const getUsageRateStatus = (rate) => {
    if (rate >= 80) return 'exception'
    if (rate >= 60) return 'warning'
    return 'success'
}

// 获取库存数量样式
const getStockClass = (row) => {
    if (row.availableQuantity === 0) {
        return 'stock-out'
    } else if (row.availableQuantity <= row.minStock) {
        return 'stock-low'
    } else if (row.availableQuantity >= row.maxStock * 0.8) {
        return 'stock-high'
    }
    return 'stock-normal'
}

// 搜索处理
const handleSearch = () => {
    stockStore.fetchStockData()
}

// 重置搜索
const handleReset = () => {
    stockStore.resetSearch()
    stockStore.fetchStockData()
}

// 刷新数据
const handleRefresh = () => {
    stockStore.fetchStockData()
}

// 导出数据
const handleExport = async () => {
    try {
        ElMessage.success('导出任务已开始，请稍后查看下载文件')
    } catch (err) {
        ElMessage.error('导出失败：' + err.message)
    }
}

// 查看详情
const handleViewDetail = (row) => {
    router.push({
        path: '/Vi/VaccineDetail',
        query: { id: row }
    })
}


// 调整库存
const handleAdjustStock = async (row) => {
    try {
        const { value } = await ElMessageBox.prompt(
            '请输入调整数量（正数为增加，负数为减少）',
            '调整库存',
            {
                inputValue: '0',
                inputPattern: /^-?\d+$/,
                inputErrorMessage: '请输入整数',
                confirmButtonText: '确认',
                cancelButtonText: '取消',
            }
        )

        const result = await stockStore.updateStockItem(row, value)

        if (result.success === true) {
            ElMessage.success('库存更新成功')
            stockStore.fetchStockData()
        } else {
            ElMessage.error(result.data.message)
        }

    } catch (err) {
        if (err !== 'cancel') {
            ElMessage.error('调整失败：' + err.message)
        }
    }
}

// 库存预警
const handleStockWarning = (row) => {
    ElMessageBox.alert(
        `<strong>${row.vaccineName}</strong><br>
    可用数量：<span style="color: ${getStockClass(row).includes('low') ? '#e6a23c' : '#f56c6c'}">${row.availableQuantity}</span><br>
    最低库存：${row.minStock}<br>
    库存状态：${stockStatusMap.value[row.stockStatus]}<br>
    使用率：${row.usageRate}%`,
        '库存预警信息',
        {
            dangerouslyUseHTMLString: true,
            type: row.availableQuantity <= row.minStock ? 'warning' : 'error'
        }
    )
}

// 分页处理
const handleSizeChange = (size) => {
    stockStore.setPagination({ pageSize: size, currentPage: 1 })
    stockStore.fetchStockData()
}

const handleCurrentChange = (page) => {
    stockStore.setPagination({ currentPage: page })
    stockStore.fetchStockData()
}

// 组件挂载时加载数据
onMounted(() => {
    stockStore.fetchStockData()
})
</script>

<style scoped>
/* 样式保持不变 */
.stock-list-container {
    padding: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.page-title {
    font-size: 18px;
    font-weight: 600;
    color: #303133;
}

.search-filter {
    margin-bottom: 16px;
}

/* 紧凑搜索样式 */
.compact-search {
    align-items: center;
}

/* 进一步缩小组件间距 */
:deep(.compact-search .el-input),
:deep(.compact-search .el-select) {
    width: 100%;
}

:deep(.compact-search .el-input__inner),
:deep(.compact-search .el-select .el-input__inner) {
    height: 32px;
    line-height: 32px;
}

.statistics-cards {
    margin-bottom: 20px;
}

.stat-card {
    border-radius: 8px;
}

.stat-item {
    display: flex;
    align-items: center;
}

.stat-icon {
    width: 48px;
    height: 48px;
    border-radius: 8px;
    display: flex;
    align-items: center;
    justify-content: center;
    margin-right: 12px;
    font-size: 24px;
    color: white;
}

.stat-icon.total {
    background: #409EFF;
}

.stat-icon.sufficient {
    background: #67C23A;
}

.stat-icon.warning {
    background: #E6A23C;
}

.stat-icon.danger {
    background: #F56C6C;
}

.stat-content {
    flex: 1;
}

.stat-value {
    font-size: 24px;
    font-weight: 600;
    color: #303133;
    line-height: 1;
}

.stat-label {
    font-size: 14px;
    color: #909399;
    margin-top: 4px;
}

.vaccine-name {
    display: flex;
    align-items: center;
    gap: 8px;
}

.name-text {
    flex: 1;
}

.stock-out {
    color: #F56C6C;
    font-weight: 600;
}

.stock-low {
    color: #E6A23C;
    font-weight: 600;
}

.stock-high {
    color: #67C23A;
    font-weight: 600;
}

.stock-normal {
    color: #409EFF;
}

.table-container {
    margin-bottom: 20px;
}

.pagination-container {
    display: flex;
    justify-content: center;
}
</style>